import axios from 'axios';
import * as qs from 'qs';
import { USE_MOCK, BACKEND_URL } from '../config/config';
import { getToken } from '../common/auth';
import router from '@/router/index'

axios.defaults.withCredentials = true

let baseConfig = {
  withCredentials: true,
  transformRequest: [
    function(data) {
      if (data instanceof FormData) {
        return data
      } else {
        return qs.stringify(data, {
          allowDots: true
        })
      }
    }
  ],
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    Token: getToken()
  }
}
if (!USE_MOCK) {
  // baseConfig['baseURL'] = 'http://47.96.11.208:80'
  baseConfig['baseURL'] = BACKEND_URL
}

let ajax = axios.create(baseConfig)
ajax.interceptors.request.use(
  config => {
    // let whiteList = ['/api/promotion/get']
    // if (whiteList.indexOf(config.url) !== -1) {
    //   config.baseURL = null
    // }
    config.headers['Token'] = getToken();
    return config
  },
  error => {
    return Promise.reject(error)
  }
)
ajax.interceptors.response.use(resp=>resp,function(err){
  if(err.response && err.response.status === 401){ // token 失效
    alert(`请重新登录！`);
    router.replace({  path: '/login'});
    location.reload();
  }
})

export default ajax
